package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.MapKey;
import com.ocom.common.dto.Department;
import com.ocom.common.entity.master.EntityDeviceLogin;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.webapi.feign.AccessClientService;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.service.AccessAccountService;
import com.ocom.webapi.vo.accessaccount.AddVo;
import com.ocom.webapi.vo.accessaccount.ModifyVo;
import com.ocom.webapi.vo.accessaccount.OnShowVo;
import com.ocom.webapi.vo.accessaccount.ResetMngUserScopeVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AccessAccountServiceImpl implements AccessAccountService {
    private final Logger log = LoggerFactory.getLogger(AccessAccountServiceImpl.class);
    @Autowired
    private AccessClientService accessClientService;


    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private HumanClientService humanClientService;

    /**
     * 账号列表（AccessAccount/onShow）
     * */
    @Override
    public Result AccessAccountOnShow(OnShowVo onShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),onShowVo.getComId());
        map.put(mapKey.getKey_agentId(),onShowVo.getAgentId());
        map.put(mapKey.getKey_deviceNo(),onShowVo.getDeviceNo());
        map.put(mapKey.getKey_loginType(),onShowVo.getLoginType());
        map.put(mapKey.getKey_account(),onShowVo.getAccount());
        map.put(mapKey.getKey_sender(),onShowVo.getSender());
        map.put(mapKey.getKey_page(),onShowVo.getPage());
        map.put(mapKey.getKey_size(),onShowVo.getSize());
        return accessClientService.GetLoginAccount(map);
    }

    /**
     * 账号修改（AccessAccount/modify）
     * */
    @Override
    public Result AccessAccountModify(ModifyVo modifyVo) {
        EntityDeviceLogin entityDeviceLogin = new EntityDeviceLogin();
        entityDeviceLogin.setId(modifyVo.getId());
        entityDeviceLogin.setComId(modifyVo.getComId());
        entityDeviceLogin.setDeviceNo(modifyVo.getDeviceNo());
        if (StringUtils.isNotEmpty(modifyVo.getAccount())){
            entityDeviceLogin.setAccount(modifyVo.getAccount());
        }
        if (StringUtils.isNotEmpty(modifyVo.getPassword())){
            entityDeviceLogin.setPassword(modifyVo.getPassword());
        }
        if (StringUtils.isNotEmpty(modifyVo.getRemark())){
            entityDeviceLogin.setRemark(modifyVo.getRemark());
        }
        if (StringUtils.isNotEmpty(modifyVo.getSender())){
            entityDeviceLogin.setSender(modifyVo.getSender());
        }
        if (StringUtils.isNotEmpty(modifyVo.getSignKey())){
            entityDeviceLogin.setSignKey(modifyVo.getSignKey());
        }
        if (StringUtils.isNotEmpty(modifyVo.getUrl())){
            entityDeviceLogin.setUrl(modifyVo.getUrl());
        }
        if (StringUtils.isNotNull(modifyVo.getLoginType())){
            entityDeviceLogin.setLoginType(modifyVo.getLoginType());
        }

        return accessClientService.UpdateLoginAccount(entityDeviceLogin);
    }

    @Override
    public Result AccessAccountDelete(Long comId, String ids) {



        return   accessClientService.DeleteLoginAccount(comId, ids);
    }
    /**
     *     账号新增（AccessAccount/add）
     */
    @Override
    public Result AccessAccountAdd(AddVo addVo) {
        EntityDeviceLogin entityDeviceLogin = new EntityDeviceLogin();

        entityDeviceLogin.setComId(addVo.getComId());
        entityDeviceLogin.setDeviceNo(addVo.getDeviceNo());
        entityDeviceLogin.setAccount(addVo.getAccount());
        entityDeviceLogin.setLoginType(addVo.getLoginType());

        if (StringUtils.isNotEmpty(addVo.getPassword())){
            entityDeviceLogin.setPassword(addVo.getPassword());
        }
        if (StringUtils.isNotEmpty(addVo.getRemark())){
            entityDeviceLogin.setRemark(addVo.getRemark());
        }
        if (StringUtils.isNotEmpty(addVo.getSender())){
            entityDeviceLogin.setSender(addVo.getSender());
        }
        if (StringUtils.isNotEmpty(addVo.getSignKey())){
            entityDeviceLogin.setSignKey(addVo.getSignKey());
        }
        if (StringUtils.isNotEmpty(addVo.getUrl())){
            entityDeviceLogin.setUrl(addVo.getUrl());
        }
        return accessClientService.AddLoginAccount(entityDeviceLogin);
    }

    /**
     * 重置账号权限范围(resetMngUserScope)
     * */
    @Override
    public Result ResetMngUserScope(ResetMngUserScopeVo resetMngUserScopeVo) {
        Map<String, Object> map1 = new HashMap<>();
        MapKey mapKey = new MapKey();
        map1.put(mapKey.getKey_id(),resetMngUserScopeVo.getPId());
        map1.put(mapKey.getKey_comId(),resetMngUserScopeVo.getComId());
        Result result = companyClientService.GetMngUserInfo(map1);
        if(result.getCode()!=200){
            throw new InvalidGrantException("用户不存在或者密码错误");
        }
        Map<String, Object> map = new HashMap<>();

        EntityMngUserInfo entityMngUserInfo= JSON.parseObject(JSON.toJSONString(result.getData()), EntityMngUserInfo.class);
        if (entityMngUserInfo.getDeptId()==0 && resetMngUserScopeVo.getKey().equals("deptId") ){
            map.put(mapKey.getKey_comId(),resetMngUserScopeVo.getComId());
            map.put(mapKey.getKey_pId(),resetMngUserScopeVo.getPId());
            map.put(mapKey.getKey_key(),resetMngUserScopeVo.getKey());
            map.put(mapKey.getKey_value(),entityMngUserInfo.getDeptId());
        }
        if (entityMngUserInfo.getDeptId() !=null &&
                entityMngUserInfo.getDeptId()>0 &&
                resetMngUserScopeVo.getKey().equals("deptId")){

                Department department = new Department();
                department.setComId(entityMngUserInfo.getComId());
                department.setDeptId(entityMngUserInfo.getDeptId());
                department.setShowLevel(0);

                log.info("防疫人员核酸变化记录表部门:department{{}}",department);
            Result deptIds = humanClientService.getDeptIds(department);
            if (deptIds.getCode()!=200){
                    return ResultUtil.error(deptIds.getCode());
                }
                log.info("防疫人员核酸变化记录表部门id:deptIds{{}}",deptIds);
            String deptIds1 = JSON.parseObject(JSON.toJSONString(deptIds.getData())).getString("deptIds");
            //不为空，代表有下属部门，
            if (!deptIds1.isEmpty()){
                String[] deptIdsStr = deptIds1.split(",");
                for (String deId: deptIdsStr) {
                    if (entityMngUserInfo.getDeptId().equals(Long.valueOf(deId))){
                        map.put(mapKey.getKey_comId(),resetMngUserScopeVo.getComId());
                        map.put(mapKey.getKey_pId(),resetMngUserScopeVo.getPId());
                        map.put(mapKey.getKey_key(),resetMngUserScopeVo.getKey());
                        map.put(mapKey.getKey_value(),deId);
                    }
                }
            }else {
                map.put(mapKey.getKey_comId(),resetMngUserScopeVo.getComId());
                map.put(mapKey.getKey_pId(),resetMngUserScopeVo.getPId());
                map.put(mapKey.getKey_key(),resetMngUserScopeVo.getKey());
                map.put(mapKey.getKey_value(),entityMngUserInfo.getDeptId());
            }
        }

        return ResultUtil.success(map);
    }


}
